<template>

  <a-card :bordered='false'style='width: 800px' title='个人信息'>
    <a-form layout="vertical" :form="form">

      <a-form-item label="生日">
        <a-date-picker
          style="width: 100%"
          placeholder="请选择生日"
          v-decorator="['birthday', {initialValue:!model.birthday?null:moment(model.birthday,dateFormat)}]"
        />
      </a-form-item>

      <a-form-item  label="性别">
        <a-select v-decorator="[ 'sex', {}]" placeholder="请选择性别">
          <a-select-option :value="1">男</a-select-option>
          <a-select-option :value="2">女</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="邮箱">
        <a-input :disable='true' placeholder="请输入邮箱" v-decorator="[ 'email', validatorRules.email]" />
      </a-form-item>

      <a-form-item label="手机号码">
        <a-input placeholder="请输入手机号码" v-decorator="[ 'phone', validatorRules.phone]" />
      </a-form-item>

      <a-form-item>
        <a-button type='primary' @click='handleSubmit' style='margin-right: 10px'>修改</a-button>
      </a-form-item>
    </a-form>

  </a-card>

</template>
<script>
import moment from 'moment'
import { mixinDevice } from '@/utils/mixin.js'
import { mapActions, mapGetters } from 'vuex'
import store from '@/store'
import { getAction } from '@api/manage'
import pick from 'lodash.pick'
import { editUser } from '@api/api'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  name:'PersonInfo',
  mixins:[mixinDevice],
  data(){
    return {
      dateFormat: "YYYY-MM-DD",
      form: this.$form.createForm(this),
      userName:this.userInfo().userName,
      userId:this.$store.state.user.name,
      userData:{},
      picUrl: '',
      model: {},
      validatorRules: {
        password: {
          rules: [
            {
              required: true,
              // pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
              message: '密码由8位数字、大小写字母和特殊符号组成!'
            },
            {
              validator: this.validateToNextPassword
            }
          ]
        },
        confirmpassword: {
          rules: [
            {
              required: true,
              message: '请重新输入登陆密码!'
            },
            {
              validator: this.compareToFirstPassword
            }
          ]
        },
        phone: { rules: [{ validator: this.validatePhone }] },
        email: {
          rules: [
            {
              validator: this.validateEmail
            }
          ]
        }
      },
      option: {
        img: '/avatar2.jpg',
        info: true,
        size: 1,
        outputType: 'jpeg',
        canScale: false,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 180,
        autoCropHeight: 180,
        fixedBox: true,
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: [1, 1]
      },
      uploadLoading: false,
      url: {
        fileUpload: window._CONFIG['domianURL'] + '/sys/common/upload',
        imgerver: window._CONFIG['domianURL'] + '/sys/common/view',
        queryUser: '/sys/user/queryUser'
      },
      headers: {}

    }
  },
  methods:{
    moment,
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let avatar = that.model.avatar
          // if(!values.birthday){
          //   values.birthday = '';
          // }else{
          //   values.birthday = values.birthday.format(this.dateFormat);
          // }
          let formData = Object.assign(this.model, values)

          formData.avatar = avatar

          editUser(formData)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    beforeUpload: function(file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
      //TODO 验证文件大小
    },
    handleChange(info) {
      this.picUrl = ''
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response
        this.uploadLoading = false
        if (response.success) {
          this.model.avatar = response.result

          this.picUrl = 'Has no pic url yet'
        } else {
          this.$message.warning(response.message)
        }
      }
    },
    getAvatarView() {
      return this.model.avatar
    },

    ...mapActions(['Logout']),
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    /*获取当前登录用户信息*/
    getAction(this.url.queryUser).then(res => {
      if (res.success) {
        let record = res.result
        this.picUrl = record.avatar
        this.model = Object.assign({}, record)
        this.form.setFieldsValue(pick(record, 'birthday', 'sex', 'email', 'mobile', 'phone'))
      }
      if (res.code === 510) {
        this.$message.warning(res.message)
      }
    })
  },
  computed: {
    uploadAction: function() {
      return this.url.fileUpload
    }
  },
}
</script>